package com.tianyi.sfzy1.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class CorsFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //cors跨域资源共享
        HttpServletResponse resp=(HttpServletResponse)servletResponse;

        //允许哪些域可以访问我们的后端接口
        resp.setHeader("Access-Control-Allow-Origin","*");
        //允许哪些请求方式
        resp.setHeader("Access-Control-Allow-Methods","POST,GET,DELETE,PUT,OPTIONS");
        //允许哪些请求头
        resp.setHeader("Access-Control-Allow-Headers","access-control-allow-origin, token, content-type, version-info, X-Requested-With");
        //预检的最大有效时间
        resp.setHeader("Access-Control-Max-Age","3600");


        //放行
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}